﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Classes;
using VAdvantage.Common;
using VAdvantage.Process; using VAdvantage.ProcessEngine;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.SqlExec;
using VAdvantage.Utility;
using VAdvantage.Controls;
using System.Data;
using System.Data.SqlClient;
using VAdvantage.Logging;
using System.Collections;
using System.Text;
using System.Threading;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace VAdvantage.Grids
{
    public abstract partial class VCreateFrom : ChildWindow
    {
        #region private variables
        //	Logger			
        private static VLogger log = VLogger.GetVLogger(typeof(VCreateFrom).FullName);
        //for select all button click
        protected int _WindowNo;//Window No               
        protected GridTab _mTab;// Model Tab        
        private bool _initOK = false;
        protected MOrder _order = null;//Loaded Order                                   
        //protected VDataGrid vdgvRecords = new VDataGrid();

        //protected Hashtable dataTable = new Hashtable();
        protected Hastable dataTable = new Hastable();
        private static String SELECT_DESELECT_ALL = "SelectDeselectAll";
        protected VLabel lblBankAccount = new VLabel();
        protected VLabel lblBPartner = new VLabel();
        protected VLabel lblOrder = new VLabel();
        protected VLabel lblInvoice = new VLabel();
        protected VLabel lblShipment = new VLabel();
        protected VLabel lblLocator = new VLabel();
        protected VAdvantage.Controls.VComboBox cmbOrder = new VAdvantage.Controls.VComboBox();
        protected VAdvantage.Controls.VComboBox cmbInvoice = new VAdvantage.Controls.VComboBox();
        protected VAdvantage.Controls.VComboBox cmbShipment = new VAdvantage.Controls.VComboBox();
        protected VComboBox cmbBankAccount;
        protected VTextBoxButton vBPartner;
        protected VTextBoxButton locatorField = new VTextBoxButton();
        //select all button status
        protected bool _checkStatus = true;
        //To button pic on grid selected records
        protected int gridCount = 0;
        //for grid header
        protected static DataGridColumn[] arrList = null;

        protected Image buttonImage = null;
        protected DataSet mainDataSet = null;
        #endregion

        public VCreateFrom()
        {
            InitializeComponent();
        }

        /// <summary>
        ///  Factory - called from APanel
        /// </summary>
        /// <param name="mTab">Model Tab for the trx</param>
        /// <returns>dialoge box</returns>
        public static VCreateFrom Create(GridTab mTab)
        {
            //	dynamic init preparation
            int AD_Table_ID = Envs.GetContext().GetContextAsInt(mTab.GetWindowNo(), "BaseTable_ID");
            VCreateFrom retValue = null;//form object
            if (AD_Table_ID == 392)             //  C_BankStatement
            {
                retValue = new VCreateFromStatement(mTab);
            }
            else if (AD_Table_ID == 318)        //  C_Invoice
            {
                retValue = new VCreateFromInvoice(mTab);
            }
            else if (AD_Table_ID == 319)        //  M_InOut
            {
                retValue = new VCreateFromShipment(mTab);
            }
            else if (AD_Table_ID == 426)		//	C_PaySelection
            {
                return null;	//	ignore - will call process C_PaySelection_CreateFrom
            }
            else    //  Not supported CreateFrom
            {
                log.Info("Unsupported AD_Table_ID=" + AD_Table_ID);
                return null;
            }
            return retValue;

        }

        /// <summary>
        /// Protected super class Constructor
        /// </summary>
        /// <param name="mTab">MTab</param>
        public VCreateFrom(GridTab mTab)
            : this()
        {
            log.Info(mTab.ToString());
            _WindowNo = mTab.GetWindowNo();
            _mTab = mTab;
            SetBusy(true);
            try
            {
                if (!DynInit())
                {
                    return;
                }
                JbInit();
                statusBar.SetStatusLine("");
                //vdgvRecords.IsReadOnly = true;
                vdgvRecords.IsReadOnly = false;
                vdgvRecords.AutoGenerateColumns = false;
                vdgvRecords.BorderThickness = new Thickness(1);
                _initOK = true;
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
                _initOK = false;
            }
            SetBusy(false);
        }

        public void EventHandler()
        {
            busyWindow.MouseLeftButtonDown += new MouseButtonEventHandler(busyWindow_MouseLeftButtonDown);

        }

        void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //throw new NotImplementedException();
            e.Handled = true;
        }

        private void SetBusy(bool value)
        {

            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }



        /// <summary>
        /// Static Init.
        /// <pre>
        /// parameterPanel
        /// parameterBankPanel
        /// parameterStdPanel
        /// bPartner/order/invoice/shopment/licator Label/Field
        /// dataPane
        /// southPanel
        /// confirmPanel
        /// statusBar
        /// </pre>
        /// </summary>
        protected virtual void JbInit()
        {
            Init();

            //this.lblBankAccount.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Top)));
            //this.lblBPartner.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Right)));
            //this.lblOrder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Right)));
            //this.lblInvoice.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Right)));
            //this.lblShipment.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Right)));
            //this.lblLocator.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Right)));

            //lblBankAccount.AutoSize = true;
            //lblBPartner.AutoSize = true;
            //lblOrder.AutoSize = true;
            //lblInvoice.AutoSize = true;
            //lblShipment.AutoSize = true;
            //lblLocator.AutoSize = true;

            lblBankAccount.Content = Msg.Translate(Envs.GetContext(), "C_BankAccount_ID");
            lblBPartner.Content = Msg.GetElement(Envs.GetContext(), "C_BPartner_ID");
            lblOrder.Content = Msg.GetElement(Envs.GetContext(), "C_Order_ID", false);
            lblInvoice.Content = Msg.GetElement(Envs.GetContext(), "C_Invoice_ID", false);
            lblShipment.Content = Msg.GetElement(Envs.GetContext(), "M_InOut_ID", false);
            lblLocator.Content = Msg.Translate(Envs.GetContext(), "M_Locator_ID");


            if (cmbBankAccount != null)
            {
                //tablePanel.Controls.Add(lblBankAccount, 0, 0);
                //tablePanel.Controls.Add(cmbBankAccount, 1, 0);

                tablePanel.Children.Add(lblBankAccount);
                lblBankAccount.Margin = new Thickness(3);
                Grid.SetColumn(lblBankAccount, 0);
                Grid.SetRow(lblBankAccount, 0);

                tablePanel.Children.Add(cmbBankAccount);
                cmbBankAccount.Margin = new Thickness(3);
                Grid.SetColumn(cmbBankAccount, 1);
                Grid.SetRow(cmbBankAccount, 0);
            }

            //if (vBPartner != null)
            //{
            //    //tablePanel.Controls.Add(lblBPartner, 0, 0);
            //    //tablePanel.Controls.Add(vBPartner, 1, 0);
            //    tablePanel.Children.Add(lblBPartner);
            //    lblBPartner.Margin = new Thickness(3);
            //    Grid.SetColumn(lblBPartner, 0);
            //    Grid.SetRow(lblBPartner, 0);

            //    tablePanel.Children.Add(vBPartner);
            //    vBPartner.Margin = new Thickness(3);
            //    Grid.SetColumn(vBPartner, 1);
            //    Grid.SetRow(vBPartner, 0);
            //}
            //tablePanel.Controls.Add(lblOrder, 2, 0);
            tablePanel.Children.Add(lblOrder);
            lblOrder.Margin = new Thickness(3);
            Grid.SetColumn(lblOrder, 2);
            Grid.SetRow(lblOrder, 0);

            //cmbOrder.Width = 120;
            //cmbOrder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            // tablePanel.Controls.Add(cmbOrder, 3, 0);
            tablePanel.Children.Add(cmbOrder);
            cmbOrder.Margin = new Thickness(3);
            Grid.SetColumn(cmbOrder, 3);
            Grid.SetRow(cmbOrder, 0);


            //tablePanel.Controls.Add(lblLocator, 0, 1);
            tablePanel.Children.Add(lblLocator);
            lblLocator.Margin = new Thickness(3);
            Grid.SetColumn(lblLocator, 0);
            Grid.SetRow(lblLocator, 1);

            //tablePanel.Controls.Add(locatorField, 1, 1);
            tablePanel.Children.Add(locatorField);
            locatorField.Margin = new Thickness(3);
            Grid.SetColumn(locatorField, 1);
            Grid.SetRow(locatorField, 1);

            //tablePanel.Controls.Add(lblInvoice, 2, 1);
            tablePanel.Children.Add(lblInvoice);
            lblInvoice.Margin = new Thickness(3);
            Grid.SetColumn(lblInvoice, 2);
            Grid.SetRow(lblInvoice, 1);

            //cmbInvoice.Width = 120;
            //cmbInvoice.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            //tablePanel.Controls.Add(cmbInvoice, 3, 1);
            tablePanel.Children.Add(cmbInvoice);
            cmbInvoice.Margin = new Thickness(3);
            Grid.SetColumn(cmbInvoice, 3);
            Grid.SetRow(cmbInvoice, 1);

            cmbShipment.Width = 180;
            //tablePanel.Controls.Add(lblShipment, 2, 1);
            tablePanel.Children.Add(lblShipment);
            lblShipment.Margin = new Thickness(3);
            Grid.SetColumn(lblShipment, 2);
            Grid.SetRow(lblShipment, 1);

            //tablePanel.Controls.Add(cmbShipment, 3, 1);
            tablePanel.Children.Add(cmbShipment);
            cmbShipment.Margin = new Thickness(3);
            Grid.SetColumn(cmbShipment, 3);
            Grid.SetRow(cmbShipment, 1);

            //selectAllButton.Image = global::VAdvantage.Properties.Resources.checkedButton;
            buttonImage = new Image();
            buttonImage.Source = Envs.LoadImageSource("checkedButton.PNG");
            btnSelectAllButton.Content = buttonImage;


            //Lookup _value = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 3499, DisplayType.Search);
            //vBPartner = new VTextBoxButton("C_BPartner_ID", false, false, true, DisplayType.Search, _value);
        }

        /// <summary>
        /// grid setting contain table design
        /// </summary>
        public virtual void Init()
        {
            //this.outerPanel.Controls.Add(this.tablePanel, 0, 0);
            //this.outerPanel.Controls.Add(this.vdgvRecords, 0, 1);
            //this.outerPanel.Controls.Add(this.bottomPanel, 0, 2);

            //form setting
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //this.tablePanel.ResumeLayout(false);
            //this.tablePanel.PerformLayout();
            //bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            //bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            //selectAllButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left)));
            //this.bottomPanel.Controls.Add(selectAllButton, 0, 0);
            //this.bottomPanel.Controls.Add(bCancel, 1, 0);
            //this.bottomPanel.Controls.Add(bOK, 2, 0);

            InfoSetting();
            this.btnOk.Click += new RoutedEventHandler(btnOk_Click);
            this.btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
            this.btnSelectAllButton.Click += new RoutedEventHandler(btnSelectAllButton_Click);
        }

        /// <summary>
        /// Table panel setting
        /// </summary>
        protected virtual void InfoSetting()
        {
            //parameter panel   
            //this.tablePanel.ColumnCount = 4;
            ////this.tablePanel.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Outset;
            //this.tablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 35F));
            //this.tablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 45F));
            //this.tablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 35F));
            //this.tablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 45F));

            //this.tablePanel.Location = new System.Drawing.Point(0, 0);
            ////this.tablePanel.Margin = new System.Windows.Forms.Padding(0);
            //this.tablePanel.RowCount = 2;
            //this.tablePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 49F));
            //this.tablePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 49F));
            //this.tablePanel.Size = new System.Drawing.Size(592, 70);
            //this.tablePanel.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.tablePanel.TabIndex = 1;

            ////bottom panel
            //this.bottomPanel.ColumnCount = 3;
            //this.bottomPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 34.93976F));
            //this.bottomPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 62F));
            //this.bottomPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 62F));

            //this.bottomPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.bottomPanel.Location = new System.Drawing.Point(0, 308);
            ////this.bottomPanel.Margin = new System.Windows.Forms.Padding(0);
            //this.bottomPanel.Margin = new Padding(0, 5, 0, 0);
            //this.bottomPanel.Name = "bottomPanel";
            //this.bottomPanel.RowCount = 1;
            //this.bottomPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100));
            ////this.bottomPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 70F));
            //this.bottomPanel.Size = new System.Drawing.Size(606, 100);
            //this.bottomPanel.TabIndex = 3;

            ////DataGrid view setting
            //this.vdgvRecords.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            //this.vdgvRecords.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.vdgvRecords.Location = new System.Drawing.Point(0, 48);
            //this.vdgvRecords.Margin = new System.Windows.Forms.Padding(0);
            //this.vdgvRecords.Size = new System.Drawing.Size(592, 249);
            //this.vdgvRecords.TabIndex = 2;
            //CommonFunctions.SetDataGridPrperties(vdgvRecords);


        }

        /// <summary>
        /// Init OK to be able to make changes?
        /// </summary>
        /// <returns>on if initialized</returns>
        public bool IsInitOK()
        {
            return _initOK;
        }

        /// <summary>
        /// Dynamic Init
        /// </summary>
        /// <returns>true if initialized</returns>
        protected abstract bool DynInit();

        /// <summary>
        /// Init Business Partner Details
        /// </summary>
        /// <param name="C_BPartner_ID">BPartner</param>
        protected abstract void InitBPDetails(int C_BPartner_ID, List<NamePair> invoice, List<NamePair> shipments);

        /// <summary>
        /// Add Info
        /// </summary>
        protected abstract void Info();

        /// <summary>
        ///  Save & Insert Data
        /// </summary>
        /// <returns>true if saved</returns>
        protected abstract bool Save();

        /// <summary>
        /// Load BPartner Field
        /// </summary>
        /// <param name="forInvoice">true if Invoices are to be created, false receipts</param>
        protected void InitBPartner(bool forInvoice)
        {
            //  load BPartner
            int AD_Column_ID = 3499;        //  C_Invoice.C_BPartner_ID
            MLookup lookup = null;
            int C_BPartner_ID = Envs.GetContext().GetContextAsInt(_WindowNo, "C_BPartner_ID");
            bool isReturnTrx = "Y".Equals(Envs.GetContext().GetContext(_WindowNo, "IsReturnTrx"));
            SetBusy(true);
            ThreadPool.QueueUserWorkItem(delegate
            {
                lookup = MLookupFactory.Get(Envs.GetContext(), _WindowNo, AD_Column_ID, DisplayType.Search);
                List<NamePair> orders = GetOrders(Envs.GetContext(), C_BPartner_ID, isReturnTrx, forInvoice);
                List<NamePair> invoices = VCreateFromShipment.GetInvoices(Envs.GetContext(), C_BPartner_ID, isReturnTrx);
                List<NamePair> shipments = VCreateFromInvoice.GetShipments(Envs.GetContext(), C_BPartner_ID);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(lookup, C_BPartner_ID, forInvoice, orders, invoices, shipments));
            });

        }
        private void InvoKFunction(Lookup lookup, int C_BPartner_ID, bool forInvoice, List<NamePair> orders, List<NamePair> invoices, List<NamePair> shipments)
        {
            SetBusy(true);
            vBPartner = new VTextBoxButton("C_BPartner_ID", true, false, true, DisplayType.Search, lookup);
            vBPartner.SetValue(C_BPartner_ID);
            if (vBPartner != null)
            {
                //tablePanel.Controls.Add(lblBPartner, 0, 0);
                //tablePanel.Controls.Add(vBPartner, 1, 0);
                tablePanel.Children.Add(lblBPartner);
                lblBPartner.Margin = new Thickness(3);
                Grid.SetColumn(lblBPartner, 0);
                Grid.SetRow(lblBPartner, 0);

                tablePanel.Children.Add(vBPartner);
                vBPartner.Margin = new Thickness(3);
                Grid.SetColumn(vBPartner, 1);
                Grid.SetRow(vBPartner, 0);
            }

            //  initial loading
            InitBPartnerOIS(C_BPartner_ID, forInvoice, orders, invoices, shipments);
            SetBusy(false);
        }

        /// <summary>
        /// Get the list of orders for a given business partner
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="C_BPartner_ID"></param>
        /// <param name="isReturnTrx"></param>
        /// <param name="forInvoice"><code>true</code> for orders matched to invoices, <code>false</code> for orders matched to shipments </param>
        /// <returns></returns>
        public static List<NamePair> GetOrders(Context ctx, int C_BPartner_ID, bool isReturnTrx, bool forInvoice)
        {
            List<NamePair> pairs = new List<NamePair>();
            // Display
            StringBuilder display = new StringBuilder("o.DocumentNo||' - ' ||").Append(
                    DB.TO_CHAR("o.DateOrdered", DisplayType.Date, Envs.GetAD_Language(ctx))).Append("||' - '||").Append(
                    DB.TO_CHAR("o.GrandTotal", DisplayType.Amount, Envs.GetAD_Language(ctx)));

            String column = "m.M_InOutLine_ID";
            if (forInvoice)
            {
                column = "m.C_InvoiceLine_ID";
            }
            DataTable dt = null;
            IDataReader idr = null;
            StringBuilder sql = new StringBuilder("SELECT o.C_Order_ID,").Append(display).Append(
                    " FROM C_Order o " + "WHERE o.C_BPartner_ID=" + C_BPartner_ID + " AND o.IsSOTrx='N' AND o.DocStatus IN ('CL','CO') "
                            + "AND o.IsReturnTrx='" + (isReturnTrx ? "Y" : "N") + "' AND o.C_Order_ID IN "
                            + "(SELECT ol.C_Order_ID FROM C_OrderLine ol"
                            + " LEFT OUTER JOIN M_MatchPO m ON (ol.C_OrderLine_ID=m.C_OrderLine_ID) "
                            + "GROUP BY ol.C_Order_ID,ol.C_OrderLine_ID, ol.QtyOrdered,").Append(column).Append(
                    " HAVING (ol.QtyOrdered <> SUM(m.Qty) AND ").Append(column).Append(" IS NOT NULL) OR ").Append(column)
                    .Append(" IS NULL) " + "ORDER BY o.DateOrdered");
            try
            {
                idr = DB.ExecuteReader(sql.ToString(), null);
                dt = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    pairs.Add(new KeyNamePair(Util.GetValueOfInt(dr[0].ToString()), dr[1].ToString()));
                }
            }
            catch (Exception e)
            {
                idr.Close();
                log.Log(Level.SEVERE, sql.ToString(), e);
            }
            return pairs;
        }

        /// <summary>
        /// Load PBartner dependent Order/Invoice/Shipment Field.
        /// </summary>
        /// <param name="C_BPartner_ID">BPartner</param>
        /// <param name="forInvoice">for invoice</param>
        protected void InitBPartnerOIS(int C_BPartner_ID, bool forInvoice, List<NamePair> orders, List<NamePair> invoices, List<NamePair> shipments)
        {
            log.Config("C_BPartner_ID=" + C_BPartner_ID);
            KeyNamePair pp = new KeyNamePair(0, "");
            //  load PO Orders - Closed, Completed
            cmbOrder.Items.Clear();
            cmbOrder.Items.Add(pp);

            //
            //bool isReturnTrx = "Y".Equals(Envs.GetContext().GetContext(_WindowNo, "IsReturnTrx"));
            //List<NamePair> orders = GetOrders(Envs.GetContext(), C_BPartner_ID, isReturnTrx, forInvoice);
            foreach (NamePair pair in orders)
            {
                cmbOrder.Items.Add(pair);
            }

            cmbOrder.SelectedIndex = 0;
            InitBPDetails(C_BPartner_ID, invoices, shipments);
        }

        /// <summary>
        /// Load Data - Order
        /// </summary>
        /// <param name="C_Order_ID">Order</param>
        /// <param name="forInvoice">true if for invoice vs. delivery qty</param>
        protected void LoadOrder(int C_Order_ID, bool forInvoice)
        {
            ThreadPool.QueueUserWorkItem(delegate
           {
               _order = new MOrder(Envs.GetContext(), C_Order_ID, null);      //  save
               //ArrayList data = GetOrderData(Envs.GetContext(), C_Order_ID, forInvoice);
               DataSet data = GetOrderData(Envs.GetContext(), C_Order_ID, forInvoice);
               //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => LoadTableOIS(data));
               System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => BindGrid(data, C_Order_ID, 0, forInvoice));

           });
            //LoadTableOIS(data);
        }

        /// <summary>
        /// get order data
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="C_Order_ID"></param>
        /// <param name="forInvoice"></param>
        /// <returns></returns>
        public static DataSet GetOrderData(Context ctx, int C_Order_ID, bool forInvoice)
        {
            /**
             *  Selected        - 0
             *  Qty             - 1
             *  C_UOM_ID        - 2
             *  M_Product_ID    - 3
             *  OrderLine       - 4
             *  ShipmentLine    - 5
             *  InvoiceLine     - 6
             */
            log.Config("C_Order_ID=" + C_Order_ID);

            //StringBuilder sql = new StringBuilder("SELECT "
            //    + "l.QtyOrdered-SUM(COALESCE(m.Qty,0)),"					//	1
            //    + "CASE WHEN l.QtyOrdered=0 THEN 0 ELSE l.QtyEntered/l.QtyOrdered END,"	//	2
            //    + " l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),"			//	3..4
            //    + " COALESCE(l.M_Product_ID,0),COALESCE(p.Name,c.Name),"	//	5..6
            //    + " l.C_OrderLine_ID,l.Line "								//	7..8
            //    + "FROM C_OrderLine l"
            StringBuilder sql = new StringBuilder("SELECT "
               + "(l.QtyOrdered-SUM(COALESCE(m.Qty,0))) * "					//	1
               + "(CASE WHEN l.QtyOrdered=0 THEN 0 ELSE l.QtyEntered/l.QtyOrdered END ) as QUANTITY,"	//	2
               + " l.C_UOM_ID  as C_UOM_ID  ,COALESCE(uom.UOMSymbol,uom.Name) as UOM,"			//	3..4
               + " COALESCE(l.M_Product_ID,0) as M_PRODUCT_ID ,COALESCE(p.Name,c.Name) as PRODUCT,"	//	5..6
               + " l.C_OrderLine_ID as C_ORDERLINE_ID,l.Line  as LINE,'false' as SELECTROW  "								//	7..8
               + " FROM C_OrderLine l"
                + " LEFT OUTER JOIN M_MatchPO m ON (l.C_OrderLine_ID=m.C_OrderLine_ID AND ");
            sql.Append(forInvoice ? "m.C_InvoiceLine_ID" : "m.M_InOutLine_ID");
            sql.Append(" IS NOT NULL)")
                .Append(" LEFT OUTER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID)"
                + " LEFT OUTER JOIN C_Charge c ON (l.C_Charge_ID=c.C_Charge_ID)");
            if (Envs.IsBaseLanguage(ctx, "C_UOM"))
            {
                sql.Append(" LEFT OUTER JOIN C_UOM uom ON (l.C_UOM_ID=uom.C_UOM_ID)");
            }
            else
            {
                sql.Append(" LEFT OUTER JOIN C_UOM_Trl uom ON (l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='")
                    .Append(Envs.GetAD_Language(ctx)).Append("')");
            }
            //
            sql.Append(" WHERE l.C_Order_ID=" + C_Order_ID			//	#1
                + "GROUP BY l.QtyOrdered,CASE WHEN l.QtyOrdered=0 THEN 0 ELSE l.QtyEntered/l.QtyOrdered END, "
                + "l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name), "
                    + "l.M_Product_ID,COALESCE(p.Name,c.Name), l.Line,l.C_OrderLine_ID "
                + "ORDER BY l.Line");
            log.Finer(sql.ToString());
            DataSet ds = DB.ExecuteDataset(sql.ToString(), null, null);
            return ds;
        }
        //public static ArrayList GetOrderData(Context ctx, int C_Order_ID, bool forInvoice)
        //{
        //    /**
        //     *  Selected        - 0
        //     *  Qty             - 1
        //     *  C_UOM_ID        - 2
        //     *  M_Product_ID    - 3
        //     *  OrderLine       - 4
        //     *  ShipmentLine    - 5
        //     *  InvoiceLine     - 6
        //     */
        //    //s_log.config("C_Order_ID=" + C_Order_ID);

        //    //Vector<Vector> data = new Vector<Vector>();
        //    ArrayList data = new ArrayList();
        //    StringBuilder sql = new StringBuilder("SELECT "
        //        + "l.QtyOrdered-SUM(COALESCE(m.Qty,0)),"					//	1
        //        + "CASE WHEN l.QtyOrdered=0 THEN 0 ELSE l.QtyEntered/l.QtyOrdered END,"	//	2
        //        + " l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),"			//	3..4
        //        + " COALESCE(l.M_Product_ID,0),COALESCE(p.Name,c.Name),"	//	5..6
        //        + " l.C_OrderLine_ID,l.Line "								//	7..8
        //        + "FROM C_OrderLine l"
        //        + " LEFT OUTER JOIN M_MatchPO m ON (l.C_OrderLine_ID=m.C_OrderLine_ID AND ");
        //    sql.Append(forInvoice ? "m.C_InvoiceLine_ID" : "m.M_InOutLine_ID");
        //    sql.Append(" IS NOT NULL)")
        //        .Append(" LEFT OUTER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID)"
        //        + " LEFT OUTER JOIN C_Charge c ON (l.C_Charge_ID=c.C_Charge_ID)");
        //    if (Envs.IsBaseLanguage(ctx, "C_UOM"))
        //    {
        //        sql.Append(" LEFT OUTER JOIN C_UOM uom ON (l.C_UOM_ID=uom.C_UOM_ID)");
        //    }
        //    else
        //    {
        //        sql.Append(" LEFT OUTER JOIN C_UOM_Trl uom ON (l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='")
        //            .Append(Envs.GetAD_Language(ctx)).Append("')");
        //    }
        //    //
        //    sql.Append(" WHERE l.C_Order_ID=" + C_Order_ID			//	#1
        //        + "GROUP BY l.QtyOrdered,CASE WHEN l.QtyOrdered=0 THEN 0 ELSE l.QtyEntered/l.QtyOrdered END, "
        //        + "l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name), "
        //            + "l.M_Product_ID,COALESCE(p.Name,c.Name), l.Line,l.C_OrderLine_ID "
        //        + "ORDER BY l.Line");
        //    //s_log.finer(sql.toString());
        //    DataTable dt = null;
        //    IDataReader idr = null;
        //    try
        //    {
        //        idr = DB.ExecuteReader(sql.ToString(), null, null);
        //        dt = new DataTable();
        //        dt.Load(idr);
        //        idr.Close();
        //        foreach (DataRow dr in dt.Rows)// while (dr.next())
        //        {
        //            //Vector<Object> line = new Vector<Object>();

        //            ArrayList line = new ArrayList();
        //            line.Add(false);           //  0-Selection
        //            Decimal qtyOrdered = Util.GetValueOfDecimal(dr[0]);//dr.getBigDecimal(1);
        //            Decimal multiplier = Util.GetValueOfDecimal(dr[1]);// dr.getBigDecimal(2);
        //            Decimal qtyEntered = Decimal.Multiply(qtyOrdered, multiplier);
        //            line.Add(Convert.ToDouble(qtyEntered));//.doubleValue()));  //  1-Qty
        //            KeyNamePair pp = new KeyNamePair(Util.GetValueOfInt(dr[2].ToString()), dr[3].ToString().Trim());
        //            line.Add(pp);                           //  2-UOM
        //            pp = new KeyNamePair(Util.GetValueOfInt(dr[4].ToString()), dr[5].ToString());
        //            line.Add(pp);                           //  3-Product
        //            pp = new KeyNamePair(Util.GetValueOfInt(dr[6].ToString()), dr[7].ToString());// new KeyNamePair(dr.getInt(7), dr.getString(8));
        //            line.Add(pp);                           //  4-OrderLine
        //            line.Add(null);                         //  5-Ship
        //            line.Add(null);                         //  6-Invoice
        //            data.Add(line);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        idr.Close();
        //        log.Log(Level.SEVERE, sql.ToString(), e);
        //    }
        //    finally
        //    {
        //        dt = null;
        //        if (idr != null)
        //        {
        //            idr.Close();
        //        }
        //    }
        //    return data;
        //}

        /// <summary>
        /// set grig header fields
        /// </summary>
        /// <param name="ctx">context</param>
        /// <returns>grid columns</returns>
        public static List<GridFieldVO> GetTableFieldVOs(Context ctx)
        {
            arrList = new DataGridColumn[7];
            List<GridFieldVO> fieldVOs = new List<GridFieldVO>();
            DataGridCheckBoxColumn chk = new DataGridCheckBoxColumn();
            chk.Header = Msg.GetMsg(Envs.GetCtx(), "Select");
            //chk.TrueValue = "True";
            //chk.FalseValue = "False";
            //chk.HeaderText = "Select";
            arrList[0] = chk;


            fieldVOs.Add(new GridFieldVO("QUANTITY", Msg.Translate(ctx, "Quantity"), FieldType.Quantity));
            DataGridTextColumn txt = new DataGridTextColumn();
            txt.Header = Msg.Translate(ctx, "Quantity");
            arrList[1] = txt;

            fieldVOs.Add(new GridFieldVO("C_UOM_ID", Msg.Translate(ctx, "C_UOM_ID"), FieldType.String));
            DataGridTextColumn txt1 = new DataGridTextColumn();
            txt1.Header = Msg.Translate(ctx, "C_UOM_ID");
            //txt1.ValueType = typeof(KeyNamePair);
            arrList[2] = txt1;

            fieldVOs.Add(new GridFieldVO("M_PRODUCT_ID", Msg.Translate(ctx, "M_Product_ID"), FieldType.String));
            DataGridTextColumn txt2 = new DataGridTextColumn();
            txt2.Header = Msg.Translate(ctx, "M_Product_ID");
            // txt2.ValueType = typeof(KeyNamePair);
            arrList[3] = txt2;

            fieldVOs.Add(new GridFieldVO("C_ORDER_ID", Msg.GetElement(ctx, "C_Order_ID", false), FieldType.String));

            DataGridTextColumn txt3 = new DataGridTextColumn();
            txt3.Header = Msg.GetElement(ctx, "C_Order_ID", false);
            // txt3.ValueType = typeof(KeyNamePair);
            arrList[4] = txt3;


            fieldVOs.Add(new GridFieldVO("M_INOUT_ID", Msg.GetElement(ctx, "M_InOut_ID", false), FieldType.String));

            DataGridTextColumn txt4 = new DataGridTextColumn();
            txt4.Header = Msg.GetElement(ctx, "M_InOut_ID", false);
            //txt4.ValueType = typeof(KeyNamePair);
            arrList[5] = txt4;


            fieldVOs.Add(new GridFieldVO("C_INVOICE_ID", Msg.GetElement(ctx, "C_Invoice_ID", false), FieldType.String));

            DataGridTextColumn txt5 = new DataGridTextColumn();
            txt5.Header = Msg.GetElement(ctx, "C_Invoice_ID", false);
            //txt5.ValueType = typeof(KeyNamePair);
            arrList[6] = txt5;

            //for( FieldVO f : fieldVOs )
            foreach (GridFieldVO f in fieldVOs)
            {
                f.IsReadOnly = true;
            }

            for (int i = 2; i < fieldVOs.Count; ++i)
            {
                fieldVOs[i].IsKey = true;
            }

            return fieldVOs;
        }
        Grids.MyDataGridCheckBoxColumn chk = new MyDataGridCheckBoxColumn();
        protected void BindGrid(DataSet ds, int C_Order_ID, int M_InOut_ID, bool forInvoice)
        {
            Ctx ctx = Envs.GetCtx();
            // clear and unbind the grid
            vdgvRecords.DataContext = null;
            vdgvRecords.ItemsSource = null;
            //vdgvQuery.DataBindings.Clear();
            vdgvRecords.Columns.Clear();
            vdgvRecords.AutoGenerateColumns = false;


            //CheckBox ch = new CheckBox();
            //ch.IsThreeState = false;
            //ch.Name = "SELECT";
            //ch.Click += new RoutedEventHandler(ch_Click);
            //ch.Content = "SELECT";

            //DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
            //templateColumn.Header = "SELECT";
            //templateColumn.CellEditingTemplate = (DataTemplate)Resources["SELECT"];
            //vdgvRecords.Columns.Add(templateColumn);


            chk.Header = Msg.GetMsg(Envs.GetCtx(), "SELECTROW");
            chk.Binding = new System.Windows.Data.Binding("SELECTROW");
            chk.DataPropertyName = "SELECTROW";
            //  chk.DataGridView = vdgvRecords;
            chk.DataGrid = vdgvRecords;
            chk.IsThreeState = false;
            chk.IsReadOnly = false;


            chk.Click += new RoutedEventHandler(chk_Click);

            chk.PropertyChanged += new PropertyChangedEventHandler(chk_PropertyChanged);
            vdgvRecords.Columns.Add(chk);

            DataGridTextColumn txt = new DataGridTextColumn();
            txt.Header = Msg.Translate(Envs.GetCtx(), "QUANTITY");
            txt.Binding = new System.Windows.Data.Binding("QUANTITY");
            txt.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt);

            DataGridTextColumn txt1 = new DataGridTextColumn();
            txt1.Header = Msg.Translate(Envs.GetCtx(), "C_UOM_ID");
            txt1.Binding = new System.Windows.Data.Binding("C_UOM_ID");
            txt1.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt1);

            DataGridTextColumn umo = new DataGridTextColumn();
            umo.Header = Msg.Translate(Envs.GetCtx(), "C_UOM_ID");
            umo.Binding = new System.Windows.Data.Binding("UOM");
            umo.IsReadOnly = true;
            vdgvRecords.Columns.Add(umo);

            DataGridTextColumn txt2 = new DataGridTextColumn();
            txt2.Header = Msg.Translate(Envs.GetCtx(), "M_PRODUCT_ID");
            txt2.Binding = new System.Windows.Data.Binding("M_PRODUCT_ID");
            txt2.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt2);

            DataGridTextColumn product = new DataGridTextColumn();
            product.Header = Msg.Translate(Envs.GetCtx(), "M_PRODUCT_ID");
            product.Binding = new System.Windows.Data.Binding("PRODUCT");
            product.IsReadOnly = true;
            vdgvRecords.Columns.Add(product);


            DataGridTextColumn txt3 = new DataGridTextColumn();
            txt3.Header = Msg.GetMsg(Envs.GetCtx(), "C_ORDERLINE_ID");
            txt3.Binding = new System.Windows.Data.Binding("C_ORDERLINE_ID");
            txt3.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt3);

            DataGridTextColumn line = new DataGridTextColumn();
            if (C_Order_ID != 0)
            {
                line.Header = Msg.GetElement(ctx, "C_Order_ID", false);
            }
            else if (M_InOut_ID != 0)
            {
                line.Header = Msg.GetElement(ctx, "M_InOut_ID", false);
            }
            else if (forInvoice)
            {
                line.Header = Msg.GetElement(ctx, "C_Invoice_ID", false);
            }

            line.Binding = new System.Windows.Data.Binding("LINE");
            line.IsReadOnly = true;
            vdgvRecords.Columns.Add(line);

            DataGridTextColumn txt4 = new DataGridTextColumn();
            if (M_InOut_ID != 0)
            {
                txt4.Header = Msg.GetElement(Envs.GetCtx(), "C_INVOICE_ID", false);
                txt4.Binding = new System.Windows.Data.Binding("C_INVOICELINE_ID");
            }
            else
            {
                txt4.Header = Msg.GetElement(Envs.GetCtx(), "M_INOUT_ID", false);
                txt4.Binding = new System.Windows.Data.Binding("M_INOUTLINE_ID");
            }
            txt4.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt4);


            DataGridTextColumn txt5 = new DataGridTextColumn();
            if (C_Order_ID != 0)
            {
                txt5.Header = Msg.GetElement(Envs.GetCtx(), "C_INVOICE_ID", false);
                txt5.Binding = new System.Windows.Data.Binding("C_INVOICE_ID");
            }
            else
            {
                txt5.Header = Msg.GetElement(Envs.GetCtx(), "C_Order_ID", false);
                txt5.Binding = new System.Windows.Data.Binding("C_Order_ID");
            }
            txt5.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt5);

            // if user has given any dataset
            if (ds != null)
            {
                //DataColumn myColumn = new DataColumn("SELECTROW");
                //myColumn.DataType = typeof(bool);
                //ds.Tables[0].Columns.Add(myColumn);
                //ds.Tables[0].Columns["SELECTROW"].Index = 0;

                // bind grid to dataset values
                vdgvRecords.ItemsSource = ds.Tables[0].GetBindableData(new Connector());
                mainDataSet = ds;
            }
            vdgvRecords.Columns[2].Visibility = System.Windows.Visibility.Collapsed;
            vdgvRecords.Columns[4].Visibility = System.Windows.Visibility.Collapsed;
            vdgvRecords.Columns[6].Visibility = System.Windows.Visibility.Collapsed;
            // vdgvRecords.Columns[8].Visibility = System.Windows.Visibility.Collapsed;
            // vdgvRecords.Columns[9].Visibility = System.Windows.Visibility.Collapsed;

            statusBar.SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "NumberOfRows") + ds.Tables[0].Rows.Count.ToString());
        }

        void chk_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {

        }

        public void chk_Click(object sender, RoutedEventArgs e)
        {
            IList list = vdgvRecords.SelectedItems;
            if (((BindableObject)list[0]).GetValue("SELECTROW") == "true" || ((BindableObject)list[0]).GetValue("SELECTROW") == "True")
            {

                ((BindableObject)vdgvRecords.SelectedItem).SetValue("SELECTROW", "false");
                mainDataSet.Tables[0].Rows[vdgvRecords.SelectedIndex]["SELECTROW"] = "false";
                gridCount--;
            }
            else if (((BindableObject)list[0]).GetValue("SELECTROW") == "false" || ((BindableObject)list[0]).GetValue("SELECTROW") == "False")
            {
                ((BindableObject)vdgvRecords.SelectedItem).SetValue("SELECTROW", "true");
                mainDataSet.Tables[0].Rows[vdgvRecords.SelectedIndex]["SELECTROW"] = "true";
                gridCount++;
            }

            // Info();
            //   if (GlobalVariable.GridRowsCount(vdgvRecords) == gridCount)
            if (list.Count == gridCount)
            {
                buttonImage = new Image();
                buttonImage.Source = Envs.LoadImageSource("UnCheked.PNG");
                btnSelectAllButton.Content = buttonImage;
                _checkStatus = false;
            }
            if (gridCount == 0)
            {
                buttonImage = new Image();
                buttonImage.Source = Envs.LoadImageSource("checkedButton.PNG");
                btnSelectAllButton.Content = buttonImage;
                _checkStatus = true;
            }
            statusBar.SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "NumberOfSelectedRows") + gridCount.ToString());
        }

        /// <summary>
        /// Load Order/Invoice/Shipment data into Table
        /// </summary>
        /// <param name="data"></param>
        protected void LoadTableOIS(ArrayList data)
        {
            //ObservableCollection<Object> datacollection = new ObservableCollection<object>();
            //DataSet ds = (DataSet)vdgvRecords.DataContext;
            //GetTableFieldVOs(Envs.GetContext());
            //for (int i = 0; i < arrList.Length; i++)
            //{
            //    vdgvRecords.Columns.Add(arrList[i]);
            //}

            //if (data != null && data.Count > 0)
            //{
            //    for (int i = 0; i < data.Count; i++)
            //    {
            //        try
            //        {
            //            //vdgvRecords.Rows.Add(1);
            //            if (ds == null)
            //            {
            //                dsMainData = new DataTable();
            //            }
            //            else
            //            {
            //                dsMainData = ds.Tables[0];
            //            }
            //            dsMainData.Rows.Add(new DataRow());

            //            ArrayList lst2 = (ArrayList)data[i];
            //            for (int j = 0; j < vdgvRecords.Columns.Count; j++)
            //            {

            //                //vdgvRecords.Rows[i].Cells[j].Value = lst2[j];
            //                dsMainData.Rows[i][j] = lst2[j];
            //                datacollection.Add(lst2[j]);
            //            }
            //        }
            //        catch
            //        {
            //        }
            //    }
            //    ds.Tables[0] = dsMainData;
            //    vdgvRecords.ItemsSource = datacollection;
            //    vdgvRecords.ItemsSource = ds.Tables[0].GetBindableData(new Connector());
            //}
            //vdgvRecords.AutoSize = true;
        }

        /// <summary>
        /// ok button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnOk_Click(object sender, RoutedEventArgs e)
        {
            //save slected records or create lines
            if (Save())
            {
                //this.Close();
                //this.DialogResult = true;
            }
        }

        /// <summary>
        /// close button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            //this.Close();
        }


        /// <summary>
        /// on button click 
        /// this show all/zero selected records
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSelectAllButton_Click(object sender, RoutedEventArgs e)
        {
            gridCount = 0;
            // select or deselect all as required
            //int rows = GlobalVariable.GridRowsCount(vdgvRecords);
            IList rowSource = vdgvRecords.ItemsSource as IList;
            int rows = rowSource.Count;


            //int rows = mainDataSet.Tables[0].Rows.Count;

            if (_checkStatus)
            {
                buttonImage = new Image();
                buttonImage.Source = Envs.LoadImageSource("checkedButton.PNG");
                btnSelectAllButton.Content = buttonImage;
                for (int i = 0; i < rows; i++)
                {
                    ((BindableObject)((ObservableCollection<object>)vdgvRecords.ItemsSource)[i]).SetValue("SELECTROW", _checkStatus.ToString().ToLower());
                    //mainDataSet.Tables[0].Rows[i]["SELECTROW"] = _checkStatus.ToString().ToLower();
                    vdgvRecords.SelectedIndex = i;
                    //((Grids.MyDataGridCheckBoxColumn)vdgvRecords.Columns[0]).SetCheckValue = _checkStatus;
                    CheckBox box = vdgvRecords.Columns[0].GetCellContent(vdgvRecords.SelectedItem) as CheckBox;
                    box.IsChecked = _checkStatus;
                    gridCount++;
                }
                _checkStatus = false;

            }
            else
            {
                buttonImage = new Image();
                buttonImage.Source = Envs.LoadImageSource("UnCheked.PNG");
                btnSelectAllButton.Content = buttonImage;
                for (int i = 0; i < rows; i++)
                {
                    ((BindableObject)((ObservableCollection<object>)vdgvRecords.ItemsSource)[i]).SetValue("SELECTROW", _checkStatus.ToString().ToLower());
                    //mainDataSet.Tables[0].Rows[i]["SELECTROW"] = _checkStatus.ToString().ToLower();
                    // ((Grids.MyDataGridCheckBoxColumn)vdgvRecords.Columns[0]).SetCheckValue = _checkStatus;
                    vdgvRecords.SelectedIndex = i;
                    CheckBox box = vdgvRecords.Columns[0].GetCellContent(vdgvRecords.SelectedItem) as CheckBox;
                    box.IsChecked = _checkStatus;
                }
                _checkStatus = true;
            }
            // Info(); 
            //vdgvRecords.ItemsSource = null;
            // vdgvRecords.ItemsSource = mainDataSet.Tables[0].GetBindableData(new Connector());
            statusBar.SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "NumberOfSelectedRows") + gridCount.ToString());
        }

        //private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    e.Handled = true;
        //}


    }

    public class MyDataGridCheckBoxColumn : DataGridCheckBoxColumn, IDataGridColumn, INotifyPropertyChanged
    {
        CheckBox chkEditing = null;
        CheckBox chkHost = null;
        GridField _field;
        private string _columnName = "";
        public event RoutedEventHandler Click = null;
        public event RoutedEventHandler Checked = null;
        bool isSeleted = false;
        CheckBox chkbox = null;
       // CheckBox chk = null;


        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            if (chkEditing != null)
            {
                chkEditing.Click -= new RoutedEventHandler(chkbox_Click);
                chkEditing = null;
                chkHost = null;
            }
            
                chkbox = (CheckBox)base.GenerateElement(cell, dataItem);
            
            //chkbox = (CheckBox)base.GenerateElement(cell, dataItem);
            //chkbox.MouseLeftButtonDown -= new MouseButtonEventHandler(chkbox_MouseLeftButtonDown);
            //chkbox.MouseLeftButtonDown += new MouseButtonEventHandler(chkbox_MouseLeftButtonDown);
            //chkbox.Click -= new RoutedEventHandler(chkbox_Click);
            //chkbox.Click += new RoutedEventHandler(chkbox_Click);
            //DataGrid.RaiseCellValueChanged(chkbox);
            //chkbox.IsHitTestVisible = true;
            return chkbox;




            // cell.IsEnabled = false;
           // CheckBox chk = (CheckBox)base.GenerateElement(cell, dataItem);
         //   chk = new CheckBox();
         //   chk.Margin = new Thickness(1);
         //   chk.BorderThickness = new Thickness(0);
         //   chk.Width = 20;
         //   chk.Height = 20;
         //   chk.Click += new RoutedEventHandler(chk_Click);
         ////   chk.Checked += new RoutedEventHandler(chk_Checked);
         //   if (DataGridView == null)
         //   {
         //       //   DataGrid.RaiseCellValueChanged(chk);
         //   }
         //   else
         //   {
         //       DataGridView.RaiseCellValueChanged(chk);
         //   }
         //   chk.IsHitTestVisible = true;
         //   // chk.IsEnabled = true;

         //   return chk;
        }

        //void chkbox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    CheckBox chkbox = (CheckBox)sender;
        //    //chkbox.Checked -= new RoutedEventHandler(chkbox_Checked);
        //    //chkbox.Unchecked -= new RoutedEventHandler(chkbox_Checked);
        //    if (Click != null)
        //    {
        //        Click(this, e);
        //    }
        //}





        void chkbox_Click(object sender, RoutedEventArgs e)
        {
            if (Click != null)
            {
                Click(this, e);

            }
        }

        ////void chk_Checked(object sender, RoutedEventArgs e)
        ////{
        ////    if (Checked != null)
        ////    {
        ////        Checked(this, e);
        ////    }
        ////}


        protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
        {

           // chkHost = cell.Content as CheckBox;

            return base.GenerateEditingElement(cell, dataItem);
        }
        protected override void RefreshCellContent(FrameworkElement element, string propertyName)
        {
            base.RefreshCellContent(element, propertyName);
        }

        protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
        {
            //////if (chkHost != null)
            //////{
            //////    chkHost.Checked -= new RoutedEventHandler(chkbox_Checked);
            //////    chkHost.Unchecked -= new RoutedEventHandler(chkbox_Checked);
            //////}



            object control = base.PrepareCellForEdit(editingElement, editingEventArgs);
            chkbox = editingElement as CheckBox;
            if (DataGridView != null)
            {
                // DataGridView.RaiseCellValueChanged(chk);

            }
            else
            {
                DataGrid.RaiseCellValueChanged(chkEditing);
            }
            chkbox.Click += new RoutedEventHandler(chkbox_Click);
            if (Click != null)
            {
                Click(this,new  RoutedEventArgs());
            }
            return control;
        }


        //void chk_Click(object sender, RoutedEventArgs e)
        //{


        //    if (Click != null)
        //    {
        //        Click(this, e);
        //    }
        //}


        public bool? GetCheckValue
        {
            get
            {
                return chkEditing.IsChecked;
            }


        }
        public bool? SetCheckValue
        {
            set
            {
                chkEditing.IsChecked = value;
            }

        }

        public string DataPropertyName
        {
            get
            {
                return _columnName;
            }

            set
            {
                _columnName = value.ToUpper();
                this.Binding = new System.Windows.Data.Binding(_columnName);
            }
        }

        public Controls.VDataGrid DataGridView
        {
            get;
            set;
        }

        public SLControls.Controls.VDataGrid DataGrid
        {
            get;
            set;
        }

        public void Dispose()
        {
            _field = null;
            chkEditing = null;
        }


        public GridField Field
        {
            get
            {
                return _field;
            }
            set
            {
                _field = value;
            }
        }

        public override System.Windows.Data.Binding Binding
        {
            get
            {
                return base.Binding;
            }
            set
            {
                base.Binding = value;
            }

        }

        public bool ReadOnly
        {

            get;
            set;

        }
        //public bool IsSelected
        //     {
        //         get
        //         {
        //             return (bool)chk.IsChecked;
        //         }
        //         set
        //         {

        //       chk.IsChecked = (bool?)value;
        //         }
        //     }


        public event PropertyChangedEventHandler PropertyChanged;


    }
}



